<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useStorage } from '@vueuse/core'
import SunIcon from './icons/SunIcon.vue'
import MoonIcon from './icons/MoonIcon.vue'

// 检查是否在客户端
const isClient = ref(false)

// 存储用户主题选择，'light' 或 'dark'
const theme = useStorage('theme', 'system')
const mounted = ref(false)
const systemTheme = ref('light')
let mediaQuery = null

// 初始化系统主题
const initSystemTheme = () => {
  if (!isClient.value) return
  try {
    systemTheme.value = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  } catch (e) {
    systemTheme.value = 'light'
  }
}

// 监听系统主题变化 - 现在不再自动跟随系统
const handleSystemThemeChange = (e) => {
  if (!isClient.value) return
  initSystemTheme()
  // 不再自动跟随系统，用户需要手动切换
}

// 应用主题到 DOM
const applyTheme = (mode) => {
  if (!isClient.value) return

  try {
    document.documentElement.classList.add('disable-transitions')

    if (mode === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }

    requestAnimationFrame(() => {
      setTimeout(() => {
        document.documentElement.classList.remove('disable-transitions')
      }, 0)
    })
  } catch (e) {
    console.error('Failed to apply theme:', e)
  }
}

// 手动切换主题
const switchTheme = () => {
  if (!isClient.value) return

  if (theme.value === 'light') {
    theme.value = 'dark'
    applyTheme('dark')
  } else {
    theme.value = 'light'
    applyTheme('light')
  }
}

// 监听主题变化
watch(theme, (newTheme) => {
  if (!isClient.value) return

  if (newTheme === 'light') {
    applyTheme('light')
  } else if (newTheme === 'dark') {
    applyTheme('dark')
  }
}, { immediate: false })

// 监听系统主题变化 - 现在只在首次初始化时使用
watch(systemTheme, (newSystemTheme) => {
  if (!isClient.value) return
  // 保留此监听器以防将来需要，但现在不再自动跟随
})

onMounted(() => {
  isClient.value = true
  mounted.value = true
  initSystemTheme()

  // 初始应用主题 - 使用系统主题作为默认
  if (theme.value === 'light') {
    applyTheme('light')
  } else if (theme.value === 'dark') {
    applyTheme('dark')
  } else {
    // 默认跟随系统
    applyTheme(systemTheme.value)
  }

  // 监听系统主题变化
  try {
    mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', handleSystemThemeChange)
  } catch (e) {
    console.error('Failed to add media query listener:', e)
  }
})

onUnmounted(() => {
  // 清理媒体查询监听器
  if (mediaQuery && isClient.value) {
    mediaQuery.removeEventListener('change', handleSystemThemeChange)
  }
})

const otherTheme = computed(() => {
  // 简单在 light 和 dark 之间切换
  return theme.value === 'dark' ? 'light' : 'dark'
})

const themeLabel = computed(() => {
  return `Switch to ${otherTheme.value} theme`
})
</script>

<template>
  <button
    type="button"
    :aria-label="mounted ? themeLabel : 'Toggle theme'"
    class="group rounded-full bg-white/90 px-3 py-2 shadow-lg ring-1 shadow-zinc-800/5 ring-zinc-900/5 backdrop-blur-sm transition dark:bg-zinc-800/90 dark:ring-white/10 dark:hover:ring-white/20"
    @click="switchTheme()"
  >
    <SunIcon class="h-6 w-6 fill-zinc-100 stroke-zinc-500 transition group-hover:fill-zinc-200 group-hover:stroke-zinc-700 dark:hidden [@media(prefers-color-scheme:dark)]:fill-primary-50 [@media(prefers-color-scheme:dark)]:stroke-primary-500 [@media(prefers-color-scheme:dark)]:group-hover:fill-primary-50 [@media(prefers-color-scheme:dark)]:group-hover:stroke-primary-600" />
    <MoonIcon class="hidden h-6 w-6 fill-zinc-700 stroke-zinc-500 transition not-[@media_(prefers-color-scheme:dark)]:fill-primary-500/10 not-[@media_(prefers-color-scheme:dark)]:stroke-primary-500 dark:block [@media(prefers-color-scheme:dark)]:group-hover:stroke-zinc-400" />
  </button>
</template>
